import { type UseQueryReturnType, useQuery } from "@tanstack/vue-query";
import { RefreshCwIcon } from "lucide-vue-next";
import { defineComponent } from "vue";
import { getJoke } from "@/apis/joke";
import Button from "@/components/Button";
import Panel from "@/components/Panel";

export default defineComponent({
  setup() {
    const query = useQuery({
      queryKey: ["joke"],
      queryFn: async () => {
        const resp = await getJoke();
        if (resp.error) {
          throw new Error("Get joke failed");
        }
        return resp.joke;
      },
    });

    return () => (
      <div class="max-w-md mx-auto mt-36">
        <Panel titleClass="justify-between">
          {{
            title: () => (
              <>
                Joke
                <Button size="sm" shape="circle" onClick={() => query.refetch()}>
                  <RefreshCwIcon />
                </Button>
              </>
            ),
            default: () => <QueriedJoke {...query} />,
          }}
        </Panel>
        <div class="mt-6 flex justify-end">
          <a href="https://jokeapi.dev/" target="__blank">
            About jokeapi.
          </a>
        </div>
      </div>
    );
  },
});

function QueriedJoke({ status, fetchStatus, data, error }: UseQueryReturnType<string, Error>) {
  if (status.value === "pending" || fetchStatus.value === "fetching") {
    return <div>Loading...</div>;
  }

  if (status.value === "error") {
    return <div>Error: {error?.value?.message}</div>;
  }

  return <div>{data.value}</div>;
}
